package com.atguigu.tingshu.user.strategy.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.SaveUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 声音购买，保存购买信息的策略实现类
 */
@Service
@Slf4j
public class UserPaidTrackStrategy implements SaveUserPaidRecordStrategy {

    @Autowired
    private UserPaidTrackService userPaidTrackService ;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient ;

    @Override
    public void saveUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {

        // 保证接口的幂等性
        String orderNo = userPaidRecordVo.getOrderNo();
        LambdaQueryWrapper<UserPaidTrack> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        lambdaQueryWrapper.eq(UserPaidTrack::getOrderNo , orderNo) ;
        List<UserPaidTrack> list = userPaidTrackService.list(lambdaQueryWrapper);
        if(!CollectionUtils.isEmpty(list)) {
            return ;
        }

        // 声音购买保存购买信息
        Long userId = userPaidRecordVo.getUserId();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();       // 购买的声音的集合

        // 根据声音的id查询声音数据
        Long trackId = itemIdList.get(0);
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(trackId);
        TrackInfo trackInfo = trackInfoResult.getData();
        Long albumId = trackInfo.getAlbumId();

        List<UserPaidTrack> paidTrackList = itemIdList.stream().map(id -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(orderNo);
            userPaidTrack.setUserId(userId);
            userPaidTrack.setAlbumId(albumId);
            userPaidTrack.setTrackId(id);
            return userPaidTrack;
        }).collect(Collectors.toList());
        userPaidTrackService.saveBatch(paidTrackList) ;

    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;
    }
}
